package com.woniuxy.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.bind.annotation.RestController;

import com.woniuxy.coder.OrderEncoder;
import com.woniuxy.pojo.Order_dgy;
import com.woniuxy.service.OrderDetailService;
import com.woniuxy.service.OrderService;
import com.woniuxy.util.WebSocketUtil;

@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")
public class WebSocketHandler {
	
	@Resource
	private OrderService orderService;
	
	@Resource
	private OrderDetailService orderDetailService;

	//建立连接
	@OnOpen
	public void openSession(@PathParam("userName")String userName,Session session){
		//将用户session存到Map中
		WebSocketUtil.MESSAGEMAP.put(userName, session);
		System.err.println(userName);
	}
	
	//发送数据
	@OnMessage
	public void onMessaage(@PathParam("userName")String userName, String message) throws EncodeException{	
		System.out.println(message);
		//判断后台页面是否打开
		String backName = "后台";
		Session session = WebSocketUtil.MESSAGEMAP.get(backName);
		if(session==null){
			WebSocketUtil.sendMessageToOne(userName, "系统维护中");
		}else{
			//判断该信息是否认证过
			if(WebSocketUtil.USERMAP.get(backName).length()==0){
				WebSocketUtil.USERMAP.put(backName, userName);
				WebSocketUtil.ORDERMAP.put(userName, message);
				//通过massage信息查找订单
				Order_dgy order_dgy = orderService.findOrderByMessage(message);
				//解码
				OrderEncoder encoder = new OrderEncoder();
				String order = encoder.encode(order_dgy);
				WebSocketUtil.sendMessageToOne(backName, order);
			}else{
				if(message.equals("清空")){
					String uName = WebSocketUtil.USERMAP.get("后台");
					String oNumber = WebSocketUtil.ORDERMAP.get(uName);
					WebSocketUtil.ORDERMAP.remove(oNumber);
					orderService.deleteOrder(oNumber);
					orderDetailService.flagOrderDetail(oNumber);
				}
				WebSocketUtil.sendMessageToOne(WebSocketUtil.USERMAP.get("后台"), message);
				WebSocketUtil.USERMAP.remove("后台");
			}	
		}
	}
	
	//关闭浏览器时关闭连接
	@OnClose
	public void onClose(@PathParam("userName")String userName, Session session){
		System.out.println(111);
		WebSocketUtil.MESSAGEMAP.remove(userName);
		//关闭session
		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//连接异常
	@OnError
	public void onError(Session session,Throwable throwable){
		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}